import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:app_core/app_core.dart';
import 'package:yh_core_flutter_project/project/common/constant/colors.dart';
import 'package:yh_core_flutter_project/project/common/constant/platform.dart';
import 'package:yh_core_flutter_project/project/common/constant/styles.dart';
import 'package:yh_core_flutter_project/project/common/managers/user_manager.dart';
import 'package:yh_core_flutter_project/project/common/utils/app_package_info.dart';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'dart:io';
import 'dart:math' as math;

import 'package:yh_core_flutter_project/project/config/app_env_config.dart';

/// 调试页面
class DebugPage extends StatefulWidget {
  const DebugPage({super.key});

  @override
  _DebugPageState createState() => _DebugPageState();
}

class _DebugPageState extends State<DebugPage> {
  EnvType _selectedEnv = EnvManager.currentEnv;
  // PackageInfo? _packageInfo;

  @override
  void initState() {
    super.initState();
    // _loadPackageInfo();
  }

  /// 加载应用信息
  // Future<void> _loadPackageInfo() async {
  //   try {
  //     final packageInfo = await PackageInfo.fromPlatform();
  //     setState(() {
  //       _packageInfo = packageInfo;
  //     });
  //   } catch (e) {
  //     debugPrint('获取应用信息失败: $e');
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text('调试页面', style: appGlobalConfig.widgetConfig.navTitleStyle),
        leading: IconButton(icon: appGlobalConfig.widgetConfig.backIcon, onPressed: () => Get.back()),

        /// 解决 iOS 导航栏滚动时的蓝色背景问题
        surfaceTintColor: Colors.transparent,

        /// 移除表面色调
        scrolledUnderElevation: 0,

        /// 滚动时移除阴影
        shadowColor: Colors.transparent,

        /// 移除阴影颜色
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              userManager.isLoggedIn ? '已登录' : '未登录',
              style: AppStyles.s18b.copyWith(color: Get.theme.colorScheme.onSurface),
            ),
            SizedBox(height: 20),
            _buildEnvironmentSection(),
            SizedBox(height: 20),
            _buildSystemInfoSection(),
            SizedBox(height: 20),
            _buildDebugToolsSection(),
            SizedBox(height: 20),
            _buildDangerZoneSection(),
          ],
        ),
      ),
    );
  }

  /// 环境切换区域
  Widget _buildEnvironmentSection() {
    return _buildSection(
      title: '环境配置',
      icon: Icons.cloud_queue,
      child: Column(
        children: [
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: AppColor.primary.withOpacity(0.1),
              border: Border.all(color: AppColor.primary.withOpacity(0.3)),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(_getEnvDisplayName(EnvManager.currentEnv), style: AppStyles.s18b.copyWith(color: AppColor.primary)),
                SizedBox(height: 4),
                Text('API: ${EnvManager.appBaseUrl}', style: AppStyles.s12.copyWith(color: AppColor.textSecondary)),
                Text('MQTT: ${EnvManager.mqttUrl}', style: AppStyles.s12.copyWith(color: AppColor.textSecondary)),
              ],
            ),
          ),
          SizedBox(height: 16),
          ...EnvType.values.map((env) => _buildEnvItem(env)),
          SizedBox(height: 16),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton.icon(
              onPressed: _selectedEnv == EnvManager.currentEnv ? null : _switchEnvironment,
              icon: Icon(Icons.swap_horiz),
              label: Text(_selectedEnv == EnvManager.currentEnv ? '当前环境' : '切换环境'),
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(vertical: 12),
                foregroundColor: Colors.white, // 文字和图标颜色
                backgroundColor: _selectedEnv == EnvManager.currentEnv ? Colors.grey[400] : AppColor.primary,
                disabledForegroundColor: Colors.grey[600], // 禁用时文字颜色
                disabledBackgroundColor: Colors.grey[300], // 禁用时背景颜色
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEnvItem(EnvType env) {
    bool isSelected = _selectedEnv == env;
    bool isCurrent = env == EnvManager.currentEnv;

    return GestureDetector(
      onTap: () => setState(() => _selectedEnv = env),
      child: Container(
        margin: EdgeInsets.only(bottom: 8),
        padding: EdgeInsets.all(12),
        decoration: BoxDecoration(
          border: Border.all(color: isSelected ? AppColor.primary : AppColor.border, width: isSelected ? 2 : 1),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Container(
              width: 20,
              height: 20,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: AppColor.border, width: 1),
                color: isSelected ? AppColor.primary : Colors.transparent,
              ),
              child: isSelected ? Icon(Icons.check, size: 14, color: AppColor.white) : null,
            ),
            SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(_getEnvDisplayName(env), style: AppStyles.s14w5.copyWith(color: isSelected ? AppColor.primary : AppColor.textPrimary)),
                      if (isCurrent) ...[
                        SizedBox(width: 8),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(color: AppColor.success, borderRadius: BorderRadius.circular(4)),
                          child: Text('当前', style: AppStyles.s10.copyWith(color: AppColor.white)),
                        ),
                      ],
                    ],
                  ),
                  Text(EnvManager.getBaseApiUrl(env), style: AppStyles.s12.copyWith(color: AppColor.textSecondary)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 系统信息区域 - 使用 AppPackageInfo 替换包信息
  Widget _buildSystemInfoSection() {
    return _buildSection(
      title: '系统信息',
      icon: Icons.info_outline,
      child: Column(
        children: [
          _buildInfoRow('应用名称', AppPackageInfo.appName),
          // _buildInfoRow('应用版本', '${AppPackageInfo.version}+${AppPackageInfo.buildNumber}'),
          _buildInfoRow('应用版本', AppPackageInfo.version),
          _buildInfoRow('包名', AppPackageInfo.packageName),
          _buildInfoRow('构建号', AppPackageInfo.buildNumber),
          _buildInfoRow('操作系统', '${Platform.operatingSystem} ${Platform.operatingSystemVersion}'),
          _buildInfoRow('设备类型', AppPlatform.displayName),
          _buildInfoRow('系统语言', AppPlatform.localeName),
        ],
      ),
    );
  }

  /// 调试工具区域
  Widget _buildDebugToolsSection() {
    return _buildSection(
      title: '调试工具',
      icon: Icons.build,
      child: Column(
        children: [
          _buildToolButton(title: '网络检测', subtitle: '测试当前网络连接状态', icon: Icons.network_check, onTap: _checkNetwork),
          _buildToolButton(
            title: '查看日志',
            subtitle: '查看应用运行日志',
            icon: Icons.list_alt,
            onTap: () {
              YHSmartDialog.showMsg('日志功能待实现');
            },
          ),
          _buildToolButton(
            title: '打印应用信息',
            subtitle: '在控制台打印详细的应用信息',
            icon: Icons.print,
            onTap: () async {
              Map<String, String> summary = await AppPackageInfo.summary;
              debugPrint(summary.toString());
            },
          ),
        ],
      ),
    );
  }

  /// 危险区域
  Widget _buildDangerZoneSection() {
    return _buildSection(
      title: '危险操作',
      icon: Icons.warning,
      titleColor: AppColor.warning,
      child: Column(
        children: [_buildToolButton(title: '模拟崩溃', subtitle: '测试崩溃日志收集功能', icon: Icons.bug_report, iconColor: AppColor.error, onTap: _simulateCrash)],
      ),
    );
  }

  Widget _buildSection({required String title, required IconData icon, required Widget child, Color? titleColor}) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(color: AppColor.white, borderRadius: BorderRadius.circular(12)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.all(16),
            child: Row(
              children: [
                Icon(icon, size: 20, color: titleColor ?? AppColor.primary),
                SizedBox(width: 8),
                Text(title, style: AppStyles.s16b.copyWith(color: titleColor ?? AppColor.primary)),
              ],
            ),
          ),
          Padding(padding: EdgeInsets.fromLTRB(16, 0, 16, 16), child: child),
        ],
      ),
    );
  }

  Widget _buildToolButton({required String title, required String subtitle, required IconData icon, required VoidCallback onTap, Color? iconColor}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: EdgeInsets.only(bottom: 8),
        padding: EdgeInsets.all(12),
        decoration: BoxDecoration(color: AppColor.white, borderRadius: BorderRadius.circular(8), border: Border.all(color: AppColor.border.withOpacity(0.5))),
        child: Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(color: (iconColor ?? AppColor.primary).withOpacity(0.1), borderRadius: BorderRadius.circular(8)),
              child: Icon(icon, color: iconColor ?? AppColor.primary, size: 20),
            ),
            SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title, style: AppStyles.s14w5),
                  SizedBox(height: 2),
                  Text(subtitle, style: AppStyles.s12.copyWith(color: AppColor.textSecondary)),
                ],
              ),
            ),
            Icon(Icons.arrow_forward_ios, size: 16, color: AppColor.textSecondary),
          ],
        ),
      ),
    );
  }

  String _getEnvDisplayName(EnvType env) {
    switch (env) {
      case EnvType.dev:
        return '开发环境';
      case EnvType.test:
        return '测试环境';
      case EnvType.release:
        return '预发布环境';
      case EnvType.prod:
        return '生产环境';
    }
  }

  void _switchEnvironment() async {
    EnvManager.currentEnv = _selectedEnv;
    setState(() {});
    YHSmartDialog.showMsg('已切换到${_getEnvDisplayName(_selectedEnv)}');
  }

  void _checkNetwork() async {
    // 1. 检测设备网络连接状态
    final connectivity = Connectivity();
    final connectivityResults = await connectivity.checkConnectivity();

    String networkType = '无网络';
    bool hasNetwork = false;

    if (connectivityResults.contains(ConnectivityResult.wifi)) {
      networkType = 'WiFi';
      hasNetwork = true;
    } else if (connectivityResults.contains(ConnectivityResult.mobile)) {
      networkType = '移动网络';
      hasNetwork = true;
    } else if (connectivityResults.contains(ConnectivityResult.ethernet)) {
      networkType = '以太网';
      hasNetwork = true;
    }

    if (!hasNetwork) {
      YHSmartDialog.dismiss();
      YHSmartDialog.showMsg('设备未连接网络');
      return;
    }

    YHSmartDialog.showMsg('$networkType网络连接正常');

    // 2. 测试API连接
    // try {
    //   final response = await HttpManager.request<Map<String, dynamic>>(
    //         path: '/health', // 假设有健康检查接口
    //         method: 'GET',
    //       );
    //   YHSmartDialog.dismiss();
    //   if (response.isSuccess) {
    //     YHSmartDialog.showMsg('网络连接正常\\n连接方式: $networkType\\nAPI服务: 正常');
    //   } else {
    //     YHSmartDialog.showMsg('网络连接正常但API异常\\n连接方式: $networkType\\nAPI错误: ${response.message}');
    //   }
    // } catch (e) {
    //   // API请求失败，但网络连接正常
    //   YHSmartDialog.dismiss();
    //   YHSmartDialog.showMsg('网络连接正常但API不可达\\n连接方式: $networkType\\n错误: $e');
    // }
  }

  void _simulateCrash() async {
    final result = await YHSmartDialog.showDangerConfirm(title: '模拟崩溃', content: '此操作将故意抛出异常，用于测试崩溃日志收集功能。应用可能会闪退。', confirmText: '确认模拟', cancelText: '取消');
    if (result == true) {
      YHSmartDialog.showMsg('即将模拟崩溃...');
      Future.delayed(Duration(seconds: 1), () {
        throw Exception('调试模式：模拟崩溃异常');
      });
    }
  }

  /// 构建信息行 - 支持同步和异步值
  Widget _buildInfoRow(String label, dynamic value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(width: 80, child: Text(label, style: AppStyles.s14.copyWith(color: AppColor.textSecondary))),
          SizedBox(width: 16),
          Expanded(
            child:
                value is Future<String>
                    ? FutureBuilder<String>(future: value, builder: (context, snapshot) => _buildClickableText(snapshot.data ?? ''))
                    : _buildClickableText(value.toString()),
          ),
        ],
      ),
    );
  }

  Widget _buildClickableText(String text) {
    return GestureDetector(
      onTap: () {
        Clipboard.setData(ClipboardData(text: text));
        YHSmartDialog.showMsg('已复制: $text');
      },
      child: SelectableText(text, style: AppStyles.s14),
    );
  }
}
